<?php
/**
 * Class Lib_SendMessage
 * 发送短信类.
 */
class Lib_SendMessage
{
    private static $obj = null;

    private $url = '/sendSMS'; //URL连接

    /**
     * 根据类型 发送短信
     */
    private $MessageType = array(
        //督促履行通知被告
        'FINANCIAL_URGE_PERFORM_RESPONDENT' => array(
            'title' => '督促履行通知被告',
            'content' => '{1}，你与{2}关于{3}经调解已达成一致，请遵照调解协议及时履行给付义务。验证码：*****，可前往广州互联网法院首页司法公开信息验证栏目进行验证。',
            'regx' => '["respondentName","applyNames","type"]',
            ),
			//调解效果通知被告
        'FINANCIAL_MEDIATION_EFFECT_RESPONDENT' => array(
            'title' => '调解效果通知被告',
            'content' => ' {1}，{2}与你方{3}一案既为自动履行债务亦未达成和解协议。现本院指定调解员{4}进行调解。限你在3日内登陆本院多元化解平台参与调解。（{5}）验证码：*****，可前往广州互联网法院首页司法公开信息验证栏目进行验证。',
            'regx' => '["respondentName","applyNames","type","master","odrUrl"]',
        ),
    );

    private function __construct()
    {
    }

    /**
     * 获取单例对象
     *
     * @param string $hl
     * @param number $timeout
     *
     * @return Lib_SendMessage
     */
    public static function getInstance()
    {
        if (is_null(self::$obj)) {
            self::$obj = new self();
        }

        return self::$obj;
    }

    // {
    // “phone”:”1560000001”,
    // “templateCode”:” MEDIATOR_EXTEND_SMS”,
    // “content”:{“”:””} //具体的key需要根据templateCode的模板来定
    // }

    /**
     * 发送短信
     data = array('caseNo' => '00000011', 'name' => 'ideal')
     */
    public function send($mobile, $data ,$caseCode, $type = 'MEDIATOR_EXTEND_SMS')
    {
        if (!$type) {
            throw new Exception("短信类型错误");
            return array();
        }
        if (!$data) {
            throw new Exception("参数错误");
            return array();
        }

        $MessageType = $this->MessageType;
        if (!isset($MessageType[$type])) {
            throw new Exception("短信类型不存在");
            return array();
        }
        
        $regx = $MessageType[$type]['regx'];
        $regx_arr = json_decode($regx, true);
        foreach ($regx_arr as $_key) {
            if (!isset($data[$_key])) {
                throw new Exception("短信参数缺失");
                return array();
            }
        }
        $post_data = array(
            'phone' => $mobile,
            'templateCode' => $type,
            'content' => $data,
            'caseCode'=>$caseCode,
        );
        $res = Lib_Request_Main::getInstance()->request($this->url, $post_data);
        if (!$res || !isset($res['code']) || $res['code']) {
            Func_Log::write('sendMessage', 'send sms error', json_encode($res));
        }

        return $res;
    }

    /**
     * 发送短信
        @explame
        $data['case_id'] = 1;
        $data['operation_uid'] = 16;
        $data['mobile'] = 15701666832;
        $data['recipient'] = 'lixiang';
        $data['recipient_type'] = 1;
        $data['scene_type'] = 1;

        $parms = array(
            'name' => 'lixiang',
            'caseNo' => 'ideal666666'
        );
     */
    public function sendMsg($data, $param, $type = 'MEDIATOR_EXTEND_SMS')
    {
        
        $result = array('code' => 1, 'msg' => 'error', 'data' => array());
        if (!$data) {
            $result['msg'] = '缺少参数';

            return $result;
        }
        if (!isset($data['case_id']) || !$data['case_id']) {
            $result['msg'] = '缺少案件号';

            return $result;
        }
        if (!isset($data['operation_uid']) && !$data['operation_uid']) {
            $result['msg'] = '缺号操作者UID';

            return $result;
        }
        if(!isset($data['caseCode']) && !$data['caseCode']) {
            $result['msg'] = '缺少法院案件号';

            return $result;
        }
        if (!isset($data['operation_name']) || !$data['operation_name']) {
            $data['operation_name'] = '';
            $res = Module_Litigation_Administrator::getInstance()->getById($data['operation_uid']);
            if ($res) {
                $data['operation_name'] = $res && isset($res['name']) ? $res['name'] : '';
            }
        }
        if (!isset($data['mobile']) || !$data['mobile']) {
            $result['msg'] = '缺少发送的手机号';

            return $result;
        }
        if (!isset($data['recipient_type']) && !$data['recipient_type']) {
            $result['msg'] = '缺少发送人类型';

            return $result;
        }

        //发送人姓名
        if (!isset($data['recipient']) || !$data['recipient']) {
            $data['recipient'] = '';
            $res = Module_Mediate_Case::getInstance()->getOne(array('defendant_name', 'plaintiff_name'), array('where' => 'id = '.$data['case_id']));
            if ($res && $data['recipient_type'] == 1) { //被告
                $data['recipient'] = $res['defendant_name'];
            } elseif ($res && $data['recipient_type'] == 2) { //原告
                $data['recipient'] = $res['plaintiff_name'];
            }
        }
        $send_status = 2; //成功
        $remark = '';
        //发送场景
        try {
            $res_send = $this->send($data['mobile'], $param,$data['caseCode'], $type);
            if (!$res_send || !isset($res_send['code']) || $res_send['code']) {
                $remark = !isset($res_send['message'])? $res_send['message'] : '';
                $send_status = 1; //失败
            }    
        } catch (Exception $e) {
            $send_status = 1;
            $remark = $e->getMessage();
        }


        $content = $this->getPostContent($type, $param);
        $data['content'] = $content;
        $data['status'] = $send_status;
        $data['remark'] = $remark;
        $data['create_ts'] = time();
        unset($data['caseCode']);
        $i = 0;
        do {
            $status = Module_Litigation_SmsLog::getInstance()->insert($data);
            ++$i;
        } while (!$status && $i < 3);
        if ($status && $send_status == 2) {
            $result['code'] = 0;
            $result['msg'] = '发送成功';

            return $result;
        }
        $result['msg'] = '发送失败';

        return $result;
    }

    /**
     * 获取发送的短信内容.
     */
    private function getPostContent($type, $param)
    {
        if (!$type || !$param) {
            return '';
        }

        $MessageType = $this->MessageType;
        if (!isset($MessageType[$type])) {
            return '';
        }
        $content = $MessageType[$type]['content'];

        $i = 1;
        foreach ($param as $_info) {
            $content = str_replace('{'.$i.'}', $_info, $content);
            ++$i;
        }

        return $content;
    }

}
